<?php
/**
 * Created by PhpStorm.
 * User: refar
 * Date: 21-7-20
 * Time: 下午5:00
 */

namespace app\v2\controller;

use think\Db;
use think\Exception;
use think\Log;

class Permission extends Common {
    /**
     * showdoc
     * @catalog 接口文档-V2/权限相关
     * @title 主界面的显示隐藏
     * @description 主界面的显示隐藏接口
     * @method post
     * @url http://domain/ems-api/v2/Permission/getItems
     * @return {"status":0,"msg":"[Permission][getItems] success","data":{"sms_btn_add":false,"sms_btn_assign":false,"sms_btn_delete":false,"sms_btn_edit":false,"sms_btn_import":false,"sms_btn_output":false,"sms_btn_return":false,"sms_btn_sale":false}}
     * @return_param status int 状态码1代表失败
     * @return_param msg string 状态码说明
     * @remark 返回0， 代表获取数据; 1.普通用户 {申请} 2. 销售管理员 {申请} {导出} {添加} {编辑} {删除} {归还} {销售} {导入} 3.PSO {申请}
     */
    public function getItems() {
        /**
         * - 普通用户 {申请}
         * - 销售管理员 {申请} {导出} {添加} {编辑} {删除} {归还} {销售} {导入}
         * - PSO {申请}
         */
        try {
            $roleId = $this->loginUser['roleId'];
            // 获得所有的button内容
            $allRights = Db::table('rights')->where('description', 'LIKE', 'sms_btn_%')->select();

            $currentRight = Db::table('role_rights')->alias('a')
                ->join('rights b', 'a.right_id=b.id')
                ->where('role_id', $roleId)->where('description', 'LIKE', 'sms_btn_%')->select();

            $in_right = [];
            foreach ($currentRight as $right) {
                $in_right[] = $right['description'];
            }

            $jsonResult = array();
            foreach ($allRights as $right) {
                if (in_array($right['description'], $in_right)) {
                    $jsonResult[$right['description']] = true;
                } else {
                    $jsonResult[$right['description']] = false;
                }

            }
            return apiResponse(SUCCESS, '[Permission][getItems] success', $jsonResult);
        } catch (Exception $e) {
            Log::record('[Permission][getItems] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
    }
    /**
     * showdoc
     * @catalog 接口文档-V2/权限相关
     * @title 侧边栏的显示隐藏
     * @description 侧边栏权限显示隐藏接口
     * @method post
     * @url http://domain/ems-api/v2/Permission/getNavBarList
     * @return {"status":0,"msg":"[Permission][getNavBarList] success","data":[{"text":"待归还","url":"\/returned","num":0},{"text":"待借出审批","url":"\/approval","num":0},{"text":"待销售审批","url":"\/sale","num":0}]}
     * @return_param url string 路由链接
     * @return_param nums int 状态数目
     * @remark 1. 普通用户 {待归还} 2. 销售管理员 {待分配} {待归还} 3. PSO / SM / GM {待销售审批} {待借出审批} {待删除审批} {待归还} 4. SM追加 {待销售确认}
     */
    public function getNavBarList() {
        // 样机状态与导航栏的对应关系
        $urlList = array('sms_nav_return'=>'/returned', 'sms_nav_assign'=>'/allocated',
            'sms_nav_borrow_review'=>'/approval', 'sms_nav_sale'=>'/sale', 'sms_nav_delete_review'=>'/delapp');

        $nameList = array('sms_nav_return'=>'待归还', 'sms_nav_assign'=>'待分配',
            'sms_nav_borrow_review'=>'待借出审批', 'sms_nav_sale'=>'销售流程', 'sms_nav_delete_review'=>'待删除审批');

        try {
            // 获取T系统账号
            $subSqlA = Db::table('role_rights')->where('role_id', $this->loginUser['roleId'])->buildSql();
            $subSqlB = Db::table('rights')->where('description', 'LIKE', 'sms_nav_%')->order('id')->buildSql();

            // 获取该账号的权限名
            $res = Db::table($subSqlA . ' a')
                ->join([$subSqlB=> 'b'], 'a.right_id=b.id')->select();

            $jsonResult = array();

            for ($i = 0; $i < count($res); $i++) {
                $desc = $res[$i]['description'];

                $tmp = array();
                $tmp['text'] = $nameList[$desc];
                $tmp['url'] = $urlList[$desc];

                /**
                 * - 普通用户 {待归还}
                 * - 销售管理员 {待分配} {待归还}
                 * - PSO / SM / GM {待销售审批} {待借出审批} {待删除审批} {待归还}
                 * - SM {待销售确认}
                 */
                // 要获取数目的话, 只能一个个判断
                if ('sms_nav_assign' == $desc) {
                    $node = Db::table('sms_approve_node')->where('remark2', '待分配=>使用中')->find();
                    $tmp['num'] = Db::table('sms_main_engine')->where('model_status', $node['target_status'])->count();
                } elseif ('sms_nav_return' == $desc) {
                    $node = Db::table('sms_approve_node')->where('remark2', '待分配=>使用中')->find();
                    $tmp['num'] = Db::table('sms_main_engine')->where('model_status', $node['next_status'])
                        ->where('user_id', $this->loginUser['T'])->count();
                } elseif ('sms_nav_borrow_review' == $desc) {
                    $borrowClassify = json_decode(BORROW_CLASSIFY, true);
                    $tmp['num'] = Db::table('sms_main_engine')->where('model_status', BORROW_REVIEW)
                        ->whereIn('department', $this->getDepartV2())
                        ->whereIn('borrow_classify', $borrowClassify[$this->loginUser['roleId']])->count();
                } elseif ('sms_nav_sale' == $desc) {
                    $node = Db::table('sms_approve_node')->where('roleId',$this->loginUser['roleId'])
                        ->where('depart', $this->loginUser['depart'])
                        ->where('flow_name', '销售')->find();

                    $tmp['num'] = Db::table('sms_main_engine')->where('model_status', $node['target_status'])->count();

                } elseif ('sms_nav_delete_review' == $desc) {
                    $deleteClassify = json_decode(DELETE_CLASSIFY, true);
                    $tmp['num'] = Db::table('sms_main_engine')->where('model_status', DELETE_REVIEW_V2)
                        ->whereIn('department', $this->getDepartV2())
                        ->whereIn('borrow_classify', $deleteClassify[$this->loginUser['roleId']])->count();
                }
                // 一般不会走到这个分支
                if (!array_key_exists('num', $tmp)) {
                    $tmp['num'] = 0;
                }
                $jsonResult[] = $tmp;
            }
            return apiResponse(SUCCESS, '[Permission][getNavBarList] success', $jsonResult);
        } catch (Exception $e) {
            Log::record('[Permission][getNavBarList] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }

    }
}